package com.rpframework.module.common.bottom.weixin.util.pay;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.SortedMap;
import java.util.TreeMap;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

/* *
 *类名：WXpayConfig
 *功能：微信支付相关配置
 */

public class WXpayConfig {
	/**
	 * 创建微信支付订单号
	 * 
	 * @return
	 */
	public static String getOutTradeNo() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
		String body = String.valueOf((int) (Math.random() * 100000000));
		String outTradeNo = "WXP" + sdf.format(new Date()) + body;
		System.out.println("创建支付订单号：" + outTradeNo);
		return outTradeNo;
	}
	
	 

	/**
	 * 创建微信预支付xml
	 * 
	 * @return
	 */
	public static String getXml(String orderNumber, float reward,String openId,String appId,String mchId,String body,String notifyUrl,String payMiyao) {
		int b = (int) reward;
		String appid = appId;
		String mch_id = mchId;// 商户号
		String nonce_str = Sha1Util.getNonceStr();// 随机字符串
		//String body = body;// 商品或支付单简要描述
		String out_trade_no = getOutTradeNo();// 订单号
		String total_fee = b + "";// 总金额
		String spbill_create_ip = "123.12.12.123";// 终端IP
		String notify_url = notifyUrl;// 通知地址
		String trade_type = "JSAPI";// 交易类型 公众号支付
		String openid = openId;// 用户ID
		String attach = orderNumber;

		SortedMap<Object, Object> packageParams = new TreeMap<Object, Object>();
		packageParams.put("appid", appid);
		packageParams.put("mch_id", mch_id);
		packageParams.put("nonce_str", nonce_str);
		packageParams.put("body", body);
		packageParams.put("total_fee", total_fee);
		packageParams.put("out_trade_no", out_trade_no);
		packageParams.put("spbill_create_ip", spbill_create_ip);
		packageParams.put("notify_url", notify_url);
		packageParams.put("trade_type", trade_type);
		packageParams.put("openid", openid);
		packageParams.put("attach", attach);
		// 生成签名
		String sign = SignUtil.createSign(packageParams, payMiyao);
		String xml = "<xml>" + "<appid>" + appid + "</appid>" + "<attach>" + attach + "</attach>" + "<mch_id>" + mch_id
				+ "</mch_id>" + "<nonce_str>" + nonce_str + "</nonce_str>" + "<body>" + body + "</body>"
				+ "<sign><![CDATA[" + sign + "]]></sign>" + "<total_fee>" + total_fee + "</total_fee>"
				+ "<out_trade_no>" + out_trade_no + "</out_trade_no>" + "<spbill_create_ip>" + spbill_create_ip
				+ "</spbill_create_ip>" + "<notify_url>" + notify_url + "</notify_url>" + "<trade_type>" + trade_type
				+ "</trade_type>" + "<openid>" + openid + "</openid>" + "</xml>";
		return xml;
	}
	
	
	/**
	 * 查询订单
	 */
	public static String getOrderXml(String orderNumber,String appId,String mchId,String payMiyao) {
		String appid = appId;
		String mch_id = mchId;// 商户号
		String nonce_str = Sha1Util.getNonceStr();// 随机字符串
		// 生成签名
		SortedMap<Object, Object> packageParams = new TreeMap<Object, Object>();
		packageParams.put("appid", appid);
		packageParams.put("mch_id", mch_id);
		packageParams.put("out_trade_no", orderNumber);
		packageParams.put("nonce_str", nonce_str);
		String sign = SignUtil.createSign(packageParams, payMiyao);
		Map<String, String> map = new HashMap<String, String>();
		map.put("appid", appid);
		map.put("mch_id", mch_id);
		map.put("out_trade_no", orderNumber);
		map.put("nonce_str", nonce_str);
		map.put("sign", sign);
		String xml = map2xml(map);
		return xml;
	}

	/**
	 * 将Map转为xml字符串
	 * 
	 * @param map
	 * @return
	 */
	public static String map2xml(Map<String, String> map) {
		StringBuilder xml = new StringBuilder();
		xml.append("<xml>\n");
		for (Map.Entry<String, String> entry : map.entrySet()) {
			xml.append("<").append(entry.getKey()).append("><![CDATA[").append(entry.getValue()).append("]]></")
					.append(entry.getKey()).append(">\n");
		}
		xml.append("</xml>");

		String ret = xml.toString();
		return ret;
	}

	/**
	 * 处理返回结果
	 * 
	 * @param args
	 * @throws Exception
	 * @throws Exception
	 */
	public static Map<String, String> confirmWeiXinReturnResponse(String xml) throws Exception {
		Map<String, String> ret = new HashMap<String, String>();
		// 将字符串转化为XML文档对象
		Document document = DocumentHelper.parseText(xml);
		// 获得文档的根节点
		Element root = document.getRootElement();
		// 遍历根节点下所有子节点
		Iterator<?> iter = root.elementIterator();

		// 遍历所有结点
		while (iter.hasNext()) {
			Element ele = (Element) iter.next();
			// 获取set方法中的参数字段（实体类的属性）
			// 调用set方法
			ret.put(ele.getName(), ele.getText());
			System.out.println(ele.getName());
			System.out.println(ele.getText());
		}
		return ret;
	}
	
	/* 
	 * 返回长度为【strLength】的随机数，在前面补0 
	 */  
	public static String getFixLenthString(int strLength) {  
	      
	    Random rm = new Random();  
	      
	    // 获得随机数  
	    int pross = (int)((1 + rm.nextDouble()) * Math.pow(10, strLength));
	  
	    // 将获得的获得随机数转化为字符串  
	    String fixLenthString = String.valueOf(pross);  
	  
	    // 返回固定的长度的随机数  
	    return fixLenthString.substring(1, strLength + 1);  
	}  
	public static void main(String[] args) {
		Long[] number=new Long[4];
		for (int i = 0; i < number.length; i++) {
			number[i]=(long)1234;
		}
		String str = Arrays.toString(number).replaceAll(", ", ",");
		str = str.substring(1, (str.length()-1));
		System.out.println(str);
	}
}
